package com.tmall.testgen.server.socket;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.tmall.testgen.common.ConnectionCommond;
import com.tmall.testgen.common.bo.interact.back.TransferCarFromServer;
import com.tmall.testgen.common.socket.SocketInfoListener;
import com.tmall.testgen.common.util.InterceptorConvertor;
import com.tmall.testgen.common.util.StringUtil;
import com.tmall.testgen.server.infocollect.DataCenter;
import com.tmall.testgen.server.socket.handler.ServerReceiveObjectHandler;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class SocketServer {


	public static ExecutorService pool = Executors.newFixedThreadPool(5);
	
	private  static  ServerSocket	ss=null;
	
	public static void stop(){
		DataCenter.isStart=false;
		try {
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void startServer() {
		try {
			ss = new ServerSocket(ConnectionCommond.PORT);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		pool.execute(new Runnable(){

			@Override
			public void run() {
				try {
					
					while (!ss.isClosed()) {
						System.out.println("等待连接..");
						Socket socket = ss.accept();
						System.out.println("连接成功..");
						SocketHandler handler=new SocketHandler();
						handler.socket=socket;
						pool.execute(handler);
					}
				} catch (Exception e) {
					//e.printStackTrace();
				}				
			}
			
		});
	}
	
	/**
	 * 为每个客户端建立一个对应的 handler
	 * @author admin
	 *
	 */
	static class SocketHandler implements Runnable{

		public  Socket socket;
	//	public ObjectOutputStream out;
		private static Object syn=new Object();
		
		@Override
		public void run() {
			try {
				//out =  new ObjectOutputStream(socket.getOutputStream());
				String uid=StringUtil.getUid();
				
				DataCenter.addUserOutPutStream(uid, socket.getOutputStream());
				
				
				
				DataCenter.getUserDatas().get(uid).writeObject(new TransferCarFromServer(TransferCarFromServer.TYPE_USER_ID,  uid));
				
				new SocketInfoListener(socket,syn,new ServerReceiveObjectHandler()).startListener();
				
				synchronized (syn) {
					syn.wait();
				}
				
				//System.out.println("移除用户："+uid);
				DataCenter.removeUser(uid);
				//out.close();
				socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
}
